/*
 * ========================================================
 * Copyright(c) 2014 杭州龙骞科技-版权所有
 * ========================================================
 * 本软件由杭州龙骞科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * http://www.hzdracom.com/
 * ========================================================
 */
package com.shwread.android.qysw.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.ConsoleMessage;
import android.webkit.JavascriptInterface;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebChromeClient.CustomViewCallback;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.shwread.android.qysw10000204.R;
import com.shwread.android.ui.widget.LoadingView;
import com.shwread.http.base.TextHttpResponseHandler;
import com.shwread.httpsdk.http.callback.BaseAction;

import org.apache.http.Header;

import logic.bean.BookInfo;
import logic.bean.TrainExamCoursewareDetailBean;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.util.Util;
import logic.util.logutil.LogUtil;


/**
 * @Project： Shwread
 * @Title：CommonWebActivity
 * @Description：
 * @Author：wayne
 * @Date：2015年3月9日上午11:29:55
 */
public class TrainExamCommonWebActivity
        extends
        BaseBusinessActivity
        implements
        OnClickListener
{
	
	private WebView            webView      = null;
	private WebChromeClient    chromeClient = null;
	private View               myView       = null; //全频时View显示
	private TextView           tvTitle      = null;
	private Button             btnBack      = null;
	private FrameLayout        fLayWebView  = null;
	private View               rlayTitle    = null;
	private CustomViewCallback myCallBack   = null;
	private LoadingView        loadingView  = null;
	
	private String             mTitle       = "";
	private String             mUrl         = "";
	private String             targetType   = "";
	private String             targetValue  = "";
	private boolean            isExam       = false;
	/** 应用是否退出 */
	private boolean            isAppExit    = false;
	private boolean            isThrough    = false;
	
	@Override
	public Handler getUIHandler() {
		return myHandler;
	}
	
	private Handler myHandler = new Handler()
	                          {
		                          
		                          @Override
		                          public void handleMessage(Message msg) {
			                          Bundle bundle = msg.getData();
			                          switch (msg.what) {
										  case 1:
											  String bookId = bundle.getString("bookId");
											  String name = bundle.getString("bookName");
											  String type = bundle.getString("bookType");
											  gotoBookDetail(bookId, name, type);
											  break;
										  case 2:
											  TrainExamCoursewareDetailBean bean = (TrainExamCoursewareDetailBean) bundle.getSerializable("detail");
											  gotoWareDetail(bean);
											  break;
										  default:
											  break;
									  }
								  }
								  
	                          };
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		setContentView(R.layout.webview_lay);
		final Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			if (bundle.containsKey(DefaultConsts.title_s)) {
				mTitle = bundle.getString(DefaultConsts.title_s);
			}
		}
		mUrl = bundle.getString(DefaultConsts.req_url_s);
		
		if (mUrl.contains("toTrainExamQuestion.do") || mUrl.contains("toEvaluatingView.do"))
		{
			//正在考试按返回弹框
			isExam = true;
		}
		initView();
		initLoadingView();
		setListener();
		setWebView();
		
		if (savedInstanceState != null)
		{
			webView.restoreState(savedInstanceState);
		}
		
	}
	
	void initView() {
		fLayWebView = (FrameLayout) findViewById(R.id.webview_flay);
		webView = (WebView) findViewById(R.id.webview_web);
		tvTitle = (TextView) findViewById(R.id.common_header_name);
		tvTitle.setText(mTitle);
		btnBack = (Button) findViewById(R.id.common_header_back);
		btnBack.setVisibility(View.VISIBLE);
		rlayTitle = findViewById(R.id.common_title_layout);
		loadingView = (LoadingView) findViewById(R.id.webview_loading_view);
	}
	
	private void initLoadingView() {
		loadingView.setLoadingAnim(R.drawable.home_progress);
		//		loadingView.setLoadingAnim(R.anim.column_switch_anim);
		loadingView.changeLoadingStatus(0);
		
		loadingView.setVisibility(View.VISIBLE);
		/** 用GONE会导致部分视频加载不出来 */
		fLayWebView.setVisibility(View.INVISIBLE);
	}
	
	void setListener() {
		btnBack.setOnClickListener(this);
	}
	
	@SuppressLint ("SetJavaScriptEnabled")
	void setWebView() {
		WebSettings webSeting = webView.getSettings();
		webSeting.setJavaScriptEnabled(true);
		webSeting.setJavaScriptCanOpenWindowsAutomatically(true);
		
		webView.setWebViewClient(new MyWebviewCient());
		
		chromeClient = new MyChromeClient();
		
		webView.setWebChromeClient(chromeClient);
		webSeting.setCacheMode(WebSettings.LOAD_NO_CACHE);
		webSeting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
		
		webView.setHorizontalScrollBarEnabled(false);
		webView.setVerticalScrollBarEnabled(true);
		
		webSeting.setSupportZoom(false);
		webSeting.setPluginState(WebSettings.PluginState.ON);
		webSeting.setLoadWithOverviewMode(true);
		webSeting.setUseWideViewPort(true); //适应屏幕
		
		if (Util.isEmpty(mUrl))
		{
			loadingView.setVisibility(View.GONE);
			fLayWebView.setVisibility(View.VISIBLE);
		}
		else
		{
			webView.loadUrl(mUrl);
		}
		
		addJavaScriptMap(new SubMaintenanceJavaScriptInterface(), "qyreader");
	}
	
	@Override
	public void onBackPressed() {
		if (myView == null)
		{
			if (isExam) sureAction();
			else
			{
				webView.onPause(); //退出播放停止
				if (webView.canGoBack() && !"5".equals(targetType)) webView.goBack();
				else
				{
					if (!existMainActivity())
					{
						startActivity(new Intent(this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP));
					}
					setResult(RESULT_OK);
					super.onBackPressed();
				}
			}
		}
		else
		{
			chromeClient.onHideCustomView();
		}
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		webView.saveState(outState);
	}
	
	public void addJavaScriptMap(Object obj, String objName) {
		webView.addJavascriptInterface(obj, objName);
	}
	
	public class MyWebviewCient
	        extends
	        WebViewClient
	{
		@Override
		public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
			WebResourceResponse response = null;
			response = super.shouldInterceptRequest(view, url);
			return response;
		}
		
		/*
		 * 点击页面的某条链接进行跳转的话，会启动系统的默认浏览器进行加载，调出了我们本身的应用
		 * 因此，要在shouldOverrideUrlLoading方法中
		 */
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			//使用当前的WebView加载页面
			if (url.contains("toTrainExamQuestion.do") || url.contains("toEvaluatingView.do"))
			{
				isExam = true;
			}
			if (url.contains("tel:"))
			{
				Intent intent = new Intent();
				intent.setAction(Intent.ACTION_DIAL);
				intent.setData(Uri.parse(url));
				startActivity(intent);
				return true;
			}
			view.loadUrl(url);
			return true;
		}
		
		/*
		 * 网页加载完毕(仅指主页，不包括图片)
		 */
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);
		}
		
		/*
		 * 网页加载完毕(仅指主页，不包括图片)
		 */
		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			if (url.contains("queryChapterInfoView.do"))
			{
				//学习记录子评测
				queryChapterInfo();
			}
			loadingView.setVisibility(View.GONE);
			fLayWebView.setVisibility(View.VISIBLE);
		}
		
		/*
		 * 加载页面资源
		 */
		@Override
		public void onLoadResource(WebView view, String url) {
			super.onLoadResource(view, url);
		}
		
		/*
		 * 错误提示
		 */
		@Override
		public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
			LogUtil.e("webview", description);
			super.onReceivedError(view, errorCode, description, failingUrl);
			loadingView.setVisibility(View.GONE);
			fLayWebView.setVisibility(View.VISIBLE);
		}
		
	}
	
	@JavascriptInterface
	public void sureAction() {
		myHandler.post(new Runnable()
		{
			@Override
			public void run() {
				//调用js中的onJsAndroid方法  
				webView.loadUrl("javascript:sureAction()");
			}
		});
	}
	
	@JavascriptInterface
	public void queryChapterInfo() {
		myHandler.post(new Runnable()
		{
			@Override
			public void run() {
				//调用js中的onJsAndroid方法  
				isThrough= true;
				webView.loadUrl("javascript:qryTrainChapterInfo()");
			}
		});
	}
	
	public class MyChromeClient
	        extends
	        WebChromeClient
	{
		
		@Override
		public void onShowCustomView(View view, CustomViewCallback callback) {
			if (myView != null)
			{
				callback.onCustomViewHidden();
				return;
			}
			fLayWebView.removeView(webView);
			fLayWebView.addView(view);
			rlayTitle.setVisibility(View.GONE);
			myView = view;
			myCallBack = callback;
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
		}
		
		@Override
		public void onHideCustomView() {
			if (myView == null) { return; }
			fLayWebView.removeView(myView);
			myView = null;
			fLayWebView.addView(webView);
			
			rlayTitle.setVisibility(View.VISIBLE);
			myCallBack.onCustomViewHidden();
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		}
		
		@Override
		public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
			Log.d("ZR", consoleMessage.message() + " at " + consoleMessage.sourceId() + ":" + consoleMessage.lineNumber());
			return super.onConsoleMessage(consoleMessage);
		}
		
		/*
		 * 此处覆盖的是javascript中的alert方法。
		 * 当网页需要弹出alert窗口时，会执行onJsAlert中的方法
		 * 网页自身的alert方法不会被调用。
		 */
		@Override
		public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
			/*
			 * 此处代码非常重要，若没有，android就不能与js继续进行交互了，
			 * 且第一次交互后，webview不再展示出来。
			 * result：A JsResult to confirm that the user hit enter.
			 * 我的理解是，confirm代表着此次交互执行完毕。只有执行完毕了，才可以进行下一次交互。
			 */
			result.confirm();
			return true;
		}
		
		/*
		 * 此处覆盖的是javascript中的confirm方法。
		 * 当网页需要弹出confirm窗口时，会执行onJsConfirm中的方法
		 * 网页自身的confirm方法不会被调用。
		 */
		@Override
		public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
			return true;
		}
		
		/*
		 * 此处覆盖的是javascript中的confirm方法。
		 * 当网页需要弹出confirm窗口时，会执行onJsConfirm中的方法
		 * 网页自身的confirm方法不会被调用。
		 */
		@Override
		public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
			return true;
		}
		
		/*
		 * 如果页面被强制关闭,弹窗提示：是否确定离开？
		 * 点击确定 保存数据离开，点击取消，停留在当前页面
		 */
		@Override
		public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) {
			return true;
		}
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.common_header_back:
				onBackPressed();
				break;
			default:
				break;
		}
		
	}
	
	private class MyHandler
	        extends
	        TextHttpResponseHandler
	{
		
		@Override
		public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
			if (isAppExit) Const.clear();
		}
		
		@Override
		public void onSuccess(int statusCode, Header[] headers, String responseString) {
			if (isAppExit) Const.clear();
		}
		
	}
	
	private class MyAction
	        extends
	        BaseAction
	{
		@Override
		public void OK(Object obj) {
			if (isAppExit) Const.clear();
		}
		
		@Override
		protected void onError() {
			super.onError();
			if (isAppExit) Const.clear();
		}
	}
	
	private void sendToastMessage(String bookId, String bookName, String bookType) {
		
		Message msg = Message.obtain();
		msg.what = 1;
		Bundle bundle = new Bundle();
		bundle.putString("bookId", bookId);
		bundle.putString("bookName", bookName);
		bundle.putString("bookType", bookType);
		msg.setData(bundle);
		myHandler.sendMessage(msg);
	}
	
	private void preGotoWareDetail(TrainExamCoursewareDetailBean bean) {
		Message msg = Message.obtain();
		msg.what = 2;
		Bundle bundle = new Bundle();
		bundle.putSerializable("detail", bean);
		msg.setData(bundle);
		myHandler.sendMessage(msg);
	}
	
	private void gotoBookDetail(String bookId, String name, String bookType) {
		if(isThrough)this.finish();
		BookInfo info = new BookInfo();
		info.setBookId(Long.parseLong(bookId));
		info.setName(name);
		info.setContent_type(bookType);
		//#ifdef SHOW_OLDBOOKDETAIL
		//$ Intent intent = new Intent(this, BookDetailActivity.class);
		//#else
		Intent intent = new Intent(this, NewBookDetailActivity.class);
		//#endif
		intent.putExtra("BookInfo", info);
		startActivity(intent);
		
	}
	
	private void gotoWareDetail(TrainExamCoursewareDetailBean bean) {
		if(isThrough)this.finish();
		Intent detailIntent = new Intent(this, CoursewareReadActivity.class);
		detailIntent.putExtra("detail", bean);
		startActivity(detailIntent);
	}
	
	final class SubMaintenanceJavaScriptInterface
	{
		
		/** 在屏幕下端提示用户 */
		@JavascriptInterface
		public void setBookInfo(String bookId, String bookName, String bookType) {
			LogUtil.d("--", "bookId：" + bookId + " | bookName:" + bookName + " |bookType:" + bookType);
			sendToastMessage(bookId, bookName, bookType);
		}
		
		/** 提供给B端打印日志 */
		@JavascriptInterface
		public void fireLog(String log) {
			LogUtil.d("dddd", log);
		}
		
		/**
		 * 假如有历史记录 回退历史记录 否则退出容器
		 */
		@JavascriptInterface
		public void goBack() {
			BaseBusinessActivity.uiHandler.post(new Runnable()
			{
				@Override
				public void run() {
					isExam = false;
					onBackPressed();
				}
			});
		}

		@JavascriptInterface
		public void setCourseInfo(String url, String page, String size, String chapterId, String name, String shortIntro, String lecturerName, String typeName, String hasExam, String evaluateType, String school) {
			TrainExamCoursewareDetailBean bean = new TrainExamCoursewareDetailBean();
			bean.setUrl(url);
			bean.setPage(Integer.parseInt(page));
			bean.setSize(Integer.parseInt(size));
			bean.setChapterId(Integer.parseInt(chapterId));
			bean.setName(name);
			bean.setShortIntro(shortIntro);
			bean.setLecturerName(lecturerName);
			bean.setHasExam(hasExam);
			bean.setEvalueteType(Integer.parseInt(evaluateType));
			bean.setTypeName(typeName);
			bean.setSchool(school);
			preGotoWareDetail(bean);
		}
	}
}
